<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="168px">
      <el-form-item label="员工名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入员工名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="签署状态-暂无" prop="contractType">
        <el-select style="width: 100%;" v-model="queryParams.contractType" placeholder="请选择签署状态" clearable>
          <el-option label="进行中" value="进行中" />
          <el-option label="已签署" value="已签署" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="statusName" type="card" @tab-click="handleClick">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAdd(1)"
          >发起签署</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            size="mini"
            @click="$router.push('/staff/template-b')"
          >合同模版管理</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            size="mini"
            @click="handleAdd(2)"
          >上传合同</el-button>
        </el-col>
      </el-row>
      <el-tab-pane label="进程中合同" name="进行中">
        <el-table v-loading="loading" :data="contractList">
          <el-table-column :formatter="defaultTableColumnDate" label="ID" align="center" prop="id" />
          <el-table-column :formatter="defaultTableColumnDate" label="合同名称" align="center" prop="contractName" />
          <el-table-column :formatter="defaultTableColumnDate" label="己签署员工" align="center" prop="signUser" />
          <el-table-column :formatter="defaultTableColumnDate" label="待签署员工" align="center" prop="unSignUser" />
          <el-table-column :formatter="defaultTableColumnDate" label="更新人" align="center" prop="updateBy" />
          <el-table-column :formatter="defaultTableColumnDate" label="更新时间" align="center" prop="updateTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :formatter="defaultTableColumnDate" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleRevoke(scope.row)"
              >撤销</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleForm(scope.row)"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                v-if="scope.row.izHistory == '是'"
                @click="handleDown(scope.row)"
              >下载PDF合同</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已签署合同" name="已签署">
        <el-table v-loading="loading" :data="contractList">
          <el-table-column :formatter="defaultTableColumnDate" label="ID" align="center" prop="id" />
          <el-table-column :formatter="defaultTableColumnDate" label="合同名称" align="center" prop="contractName" />
          <el-table-column :formatter="defaultTableColumnDate" label="签署员工" align="center" prop="signUser" />
          <el-table-column :formatter="defaultTableColumnDate" label="更新人" align="center" prop="updateBy" />
          <el-table-column :formatter="defaultTableColumnDate" label="更新时间" align="center" prop="updateTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column :formatter="defaultTableColumnDate" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleForm(scope.row)"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                v-if="scope.row.izHistory == '是'"
                @click="handleDown(scope.row)"
              >下载PDF合同</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog destroy-on-close :title="title" :visible.sync="open1" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="发起方式" prop="initiationMethod">
          <el-radio-group v-model="form.initiationMethod">
            <el-radio label="选择合同模版">选择合同模版</el-radio>
            <el-radio label="导入本地文件">导入本地文件</el-radio>
          </el-radio-group>
          <!-- <el-button
            type="primary"
            style="margin-left: 20px;"
            plain
            size="mini"
            @click="jumpDZQ()"
          >进入平台模板</el-button> -->
        </el-form-item>
        <el-form-item label="合同模板类型" prop="templateType" v-if="form.initiationMethod=='选择合同模版'">
          <el-radio-group v-model="form.templateType">
            <el-radio
              v-for="dict in dict.type.template_type"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="合同模版" prop="contractUrl" v-if="form.initiationMethod=='选择合同模版'">
          <el-select style="width: 100%;" v-model="form.contractUrl" placeholder="请选择合同模版">
            <el-option
              v-for="item in templateList"
              :key="item.templateUrl"
              :label="item.templateName"
              :value="item.templateUrl"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同文件" v-if="form.initiationMethod=='导入本地文件'">
          <el-upload
            :action="baseUrl + '/common/uploadTempFile'"
            :headers="{
              'Authorization': 'Bearer ' + getToken(),
            }"
            accept=".doc,.docx,.pdf"
            :on-success="handleSuccess"
            :limit="1">
            <div>
              <el-button size="small" type="primary">上传文件</el-button>
              <span slot="tip" class="el-upload__tip" style="margin-left: 20px;">支持扩展名：.doc .docx .pdf</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="签署对象" required>
          <el-checkbox v-model="statusFlag">仅显示在职员工</el-checkbox>
          <div style="height: 400px;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);overflow-y: auto;padding: 20px;">
            <el-row :gutter="10" class="mb8">
              <el-col :span="12">
                <el-input v-model="searchVal" placeholder="请输入"></el-input>
              </el-col>
              <el-col :span="12">
                <el-button type="primary" @click="search">搜索</el-button>
              </el-col>
            </el-row>
            <el-checkbox-group v-model="checkedList">
              <div v-for="item in treeList" :key="item.id">
                <el-checkbox :label="item.id">{{ item.staffName }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">
          <!-- {{form.initiationMethod=='选择合同模版' && form.templateType == '平台模板'?'填写合同正文':'确定'}} -->
          填写合同正文
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog destroy-on-close :title="title" :visible.sync="open2" width="1000px" append-to-body>
      <el-form label-width="120px">
        <el-form-item label="合同文件" required>
          <el-upload
            :action="baseUrl + '/common/uploadTempFile'"
            :headers="{
              'Authorization': 'Bearer ' + getToken(),
            }"
            accept=".doc,.docx,.pdf"
            :on-success="handleSuccess"
            :limit="1">
            <div>
              <el-button size="small" type="primary">上传文件</el-button>
              <span slot="tip" class="el-upload__tip" style="margin-left: 20px;">支持扩展名：.doc .docx .pdf</span>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="关联员工" required>
          <el-checkbox v-model="statusFlag">仅显示在职员工</el-checkbox>
          <div style="height: 400px;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);overflow-y: auto;padding: 20px;">
            <el-row :gutter="10" class="mb8">
              <el-col :span="12">
                <el-input v-model="searchVal" placeholder="请输入"></el-input>
              </el-col>
              <el-col :span="12">
                <el-button type="primary" @click="search">搜索</el-button>
              </el-col>
            </el-row>
            <el-checkbox-group v-model="checkedList">
              <div v-for="item in treeList" :key="item.id">
                <el-checkbox :label="item.id">{{ item.staffName }}</el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadContract">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { authenticationOrConsole, listContract, getContract, contractRevoke, addContract, addSign, getDownUrl } from "@/api/system/contract";
import { listGsTemplateList, listPtTemplateList, getTemplateUrl } from "@/api/system/template";
import { getListStaff } from "@/api/system/staff";

export default {
  name: "Contract",
  dicts: ['template_type', 'contract_type'],
  data() {
    return {
      searchVal: '',
      templateList: [],
      checkedList: [],
      statusFlag: true,
      treeList: [],
      oldTreeList: [],
      getToken,
      baseUrl: process.env.VUE_APP_BASE_API,
      fileUrl: '',
      fileName: '',
      statusName: '已签署',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open1: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        contractName: null,
        templateType: null,
        contractUrl: null,
        initiationMethod: null,
        contractType: null,
        startDate: null,
        endDate: null,
        contractId: null,
        status: null,
        message: null,
        izHistory: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractName: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        contractUrl: [
          { required: true, message: "合同模版不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    statusFlag() {
      this.getTree();
    },
    'form.initiationMethod'(n) {
      if(n == '导入本地文件') {
        this.form.templateType = ''
      } else {
        this.form.templateType = '选择合同模版'
      }
      this.form.contractUrl = ''
      this.fileUrl = ''
    },
    'form.templateType'(n) {
      if(n) {
        this.form.contractUrl = ''
        this.templateList = []
        this.getTemplateList()
      }
    },
  },
  created() {
    if (this.$route.query.contractType) {
      this.queryParams.contractType = this.$route.query.contractType;
      this.statusName = this.$route.query.contractType;
    } else {
      this.queryParams.contractType = null;
      this.statusName = "已签署";
    }
    this.getList();
    this.getTree();
  },
  mounted() {
    this.handleVisibilityChange = this.handleVisibilityChange.bind(this);
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
  },
  beforeDestroy() {
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
  },
  methods: {
    async jumpDZQ() {
      const res = await authenticationOrConsole({})
      window.open(res.data.pc)
    },
    handleVisibilityChange() {
      if (document.visibilityState === 'visible') {
        this.getList();
      }
    },
    handleForm(row) {
      if(row.izHistory == '是') {
        const url = this.baseUrl + row.contractUrl
        window.open(url)
      } else {
        getDownUrl(row).then(response => {
          const previewUrl = response.data.url2
          window.open(previewUrl)
        })
      }
    },
    base64DownloadFile(url, fileName) {
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
      link.click();
    },
    handleDown(row) {
      if(row.izHistory == '是') {
        const url = this.baseUrl + row.contractUrl
        this.base64DownloadFile(url, row.contractUrl.split('/').slice(-1)[0])
      } else {
        getDownUrl(row).then(response => {
          const previewUrl = response.data.url2
          window.open(previewUrl)
        })
      }
    },
    /** 查询合同模版管理列表 */
    getTemplateList() {
      this.$modal.loading()
      if(this.form.templateType=='公司模板') {
        // listGsTemplateList({templateType: '员工关系'}).then(response => {
        //   this.$modal.closeLoading()
        //   this.templateList = response.data;
        // });
        listPtTemplateList({userFlowTypeId: 'yDtIXUU2wpi5fkUuJ2FuPvVksmdkur0a', systemType: '公司'}).then(response => {
          this.$modal.closeLoading()
          this.templateList = response.data;
          this.templateList.forEach( t => {
            t.templateUrl = t.templateId
          })
        });
      } else {
        listPtTemplateList({userFlowTypeId: 'yDtIXUU2wpi5fkUuJ2FuPvVksmdkur0a', systemType: '平台'}).then(response => {
          this.$modal.closeLoading()
          this.templateList = response.data;
          this.templateList.forEach( t => {
            t.templateUrl = t.templateId
          })
          console.log(this.templateList);
        });
      }
    },
    handleSuccess(file) {
      this.fileUrl = file.fileName
      this.fileName = file.newFileName
    },
    search() {
      if(this.searchVal) {
        this.treeList = this.oldTreeList.filter(v => v.staffName.includes(this.searchVal))
      } else {
        this.treeList = this.oldTreeList
      }
    },
    getTree() {
      getListStaff({status: this.statusFlag?'在职':'离职'}).then(response => {
        this.treeList = response.data
        this.oldTreeList = response.data
        this.searchVal = ''
      });
    },
    handleClick(tab, event) {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listContract({...this.queryParams, statusName: this.statusName, contractType: '员工关系'}).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open1 = false;
      this.open2 = false;
      this.reset();
      this.fileName = ''
      this.fileUrl = ''
      this.checkedList = []
      this.statusFlag = true
      this.searchVal = ''
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyId: null,
        contractName: null,
        templateType: '公司模板',
        contractUrl: null,
        initiationMethod: '选择合同模版',
        contractType: null,
        startDate: null,
        endDate: null,
        contractId: null,
        status: null,
        message: null,
        izHistory: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(e) {
      this.reset();
      if(e == 1) {
        const enterpriseInfo = this.$store.getters.enterpriseInfo
        if(!enterpriseInfo) {
          this.$modal.msg(`请使用企业账号!`);
          return
        }
        if(enterpriseInfo.contractAllNum - enterpriseInfo.contractUseNum <= 0) {
          this.$modal.confirm('剩余合同份数余额不足，是否立即充值？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(({ value }) => {
            this.$router.push("/b/platfromEquity");
          }).catch(() => {
          });
          return
        }
        this.open1 = true;
        this.title = "发起签署";
      } else {
        this.open2 = true;
        this.title = "上传合同";
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.initiationMethod=='导入本地文件') {
            if(!this.fileUrl) {
              // this.$modal.msg(`请上传文件!`);
              // return
            } else {
              this.form.contractUrl = this.fileUrl
            }
          }
          if(!this.checkedList.length) {
            this.$modal.msg(`请选择员工!`);
            return
          }
          addSign({...this.form, userIds: this.checkedList.join(','), contractType: '员工关系'}).then(response => {
            this.open = false;
            this.getList();
            if(response.data.prepareFlowUrl) {
              this.$modal.msgSuccess("链接有效期五分钟，请尽快填写");
              setTimeout(() => {
                window.open(response.data.prepareFlowUrl)
              }, 1000)
            } else {
              this.$modal.msg("获取合同链接失败");
            }
          });
          // if((this.form.initiationMethod=='选择合同模版' && this.form.templateType == '平台模板') || this.form.initiationMethod=='导入本地文件') {
          //   addSign({...this.form, userIds: this.checkedList.join(','), contractType: '员工关系'}).then(response => {
          //     if(response.data.prepareFlowUrl) {
          //       this.$modal.msgSuccess("链接有效期五分钟，请尽快填写");
          //       setTimeout(() => {
          //         window.open(response.data.prepareFlowUrl)
          //       }, 1000)
          //     } else {
          //       this.$modal.msg("获取合同链接失败");
          //     }
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
          //   addSign({...this.form, userIds: this.checkedList.join(','), contractType: '员工关系'}).then(response => {
          //     this.$modal.msgSuccess("新增成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // }
        }
      });
    },
    uploadContract() {
      if(!this.fileUrl) {
        this.$modal.msg(`请上传文件!`);
        return
      }
      if(!this.checkedList.length) {
        this.$modal.msg(`请选择员工!`);
        return
      }
      const params = {
        contractUrl: this.fileUrl,
        contractName: this.fileName,
        userIds: this.checkedList.join(','),
        contractType: '员工关系'
      }
      addContract(params).then(response => {
        this.$modal.msgSuccess("上传成功");
        this.open2 = false;
        this.getList();
      });
    },
    /** 撤销按钮操作 */
    handleRevoke(row) {
      const ids = row.id || this.ids;
      const that = this
      this.$prompt('是否确认撤销合同编号为"' + ids + '"的数据项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          if(!value) {
            that.$modal.msg(`请输入撤销原因!`);
            return
          }
          return contractRevoke({id: ids, cancelMessage: value})
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("撤销成功");
        }).catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
